#!/bin/bash

get_location_id="$(realpath "$0")"
get_location_id="${get_location_id%/*}/get_location_id"

for d in yad grep sed "$get_location_id"; do 
    type -f $d >/dev/null || exit 1
done

confdir="${XDG_CONFIG_HOME-"$HOME/.config"}/fmi-weather"
locations_file="$confdir/selected_locations"
conf="$confdir/conf"
nl=$'\n'
result=''
selloc=() # selected locations
yadcmd=(yad --center --window-icon weather --title "Weather locations" --button=Cancel:252 )

search_and_select() {
    query=''
    while [ -z "$query" ]; do
        fuzzy=''
        query="$("${yadcmd[@]}" --entry-label "Enter location query" --button=Search:0 --button=Fuzzy\ search:222 --entry)"
        case $? in
            252) return
            ;;
            222) fuzzy="-f"
            ;;
        esac
    done
    mapfile -t morloc < <("$get_location_id" $fuzzy "$query")
    result="$("${yadcmd[@]}" --entry-label "Add location" --button=OK:0 --entry "${morloc[@]}")"
    case $? in
        252) return
        ;;
    esac
}

if [ -r "$locations_file" ]; then
    mapfile -t selloc <"$locations_file"
else
    search_and_select
    selloc=( "$result" )
fi

while [ -z "$result" ]; do
    result="$("${yadcmd[@]}" --entry-label "Choose location" --button=OK:0 --button=Add\ more:222 --entry "${selloc[@]}")"
    case $? in
        252) exit
        ;;
        222) search_and_select
        ;;
    esac
    result="${result%"${result##*[![:space:]]}"}"
    selloc=( "$result" "$(for i in "${selloc[@]}"; do [[ "$i" == "$result" ]] && continue; echo "$i"; done)" )
done

mkdir -p "$confdir"

if [ -r "$conf" ]; then
    ere='^[[:space:]]*geoid=[0-9]+'
    grep -qE "$ere" "$conf" && sed -Ei "s/$ere/geoid=${result%% *}/" "$conf" || echo "geoid=${result%% *}" >> "$conf"
else
    echo "geoid=${result%% *}" > "$conf"
fi

for i in "${selloc[@]}"; do echo "$i"; done > "$locations_file"
